var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');


var YjxTmplSetModel = function (obj) {
    YjxBaseModel.call(this,obj);

    // `set_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '模版组id',
    // `title` varchar(50) NOT NULL DEFAULT '' COMMENT '编组名称',
    // `desc` varchar(500) DEFAULT '' COMMENT '用途简介',
    // `use` int(3) NOT NULL DEFAULT '0' COMMENT '用途: [保留字段]',
    // `thumb` text COMMENT '图示: [保留字段]',
    // `order` int(3) NOT NULL DEFAULT '999' COMMENT '显示顺序',
    // `start_time` datetime DEFAULT NULL COMMENT '有效开始日期: [保留字段]',
    // `end_time` datetime DEFAULT NULL COMMENT '有效截止日期 [保留字段]',
    // `publish` int(1) NOT NULL DEFAULT '0' COMMENT '1发布, 0未发布',
    // `create_time` datetime NOT NULL,
    // `update_time` datetime NOT NULL,
    // `update_by` varchar(50) NOT NULL DEFAULT '',
    // `del_flg` int(1) NOT NULL DEFAULT '0',
    // PRIMARY KEY (`set_id`)

};

YjxTmplSetModel.prototype = new YjxBaseModel();

// 取得表名
YjxTmplSetModel.prototype.getTableName = function(){
    return 'yjx_tmpl_set';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxTmplSetModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'set_id='+this.set_id;
};

/**
 * 获取查询 指定范围模板组内模板列表/数量 的 sql
 *
 * @author 王俊
 * @date   2017-11-16
 *
 * @param bForCnt true 标识获取一个查询指定范围模板组内包含模板个数的 sql, false 标记获取列表的 sql
 * @param setIds 模板组 id 的数组
 * @param pageNum 页码
 * @param pageSize 页容量
 *
 * @return 对应类型的 sql
 * */
function sql_getSetsTmplsList(bForCnt, setIds, pageNum, pageSize) {

    var ids = setIds.join(',');
    var sql = '';
    if(bForCnt) {
        sql += ' SELECT COUNT(0) as count ';
    } else  {
        sql += ' SELECT mix.*, ' +
               '        if(uts.show_apply_cnt != NULL, uts.show_apply_cnt, 0) AS useCounts ';
    }
    sql += ' FROM ' +
    '   (SELECT utd.uni_item_id AS id, ' +
    '           tdd.design_name AS name, ' +
    '           1 AS opType, ' +
    '           tdp.thumb, ' +
    '           ts.width AS w, ' +
    '           ts.height AS h, ' +
    '           iu.nickname AS author, ' +
    '           DATE_FORMAT(tdd.create_time,"%Y-%m-%d %H:%i:%s") AS time, ' +
    '           yst.title AS typeDesc, ' +
    '           utd.order ' +
    '    FROM yjx.yjx_tmpl_set_r tsr, ' +
    '         yjx.yjx_uni_items utd, ' +
    '         itbour.tg_design_doc tdd, ' +
    '         yjx.yjx_show_type yst, ' +
    '         yjx.yjx_show_type_r ystr, ' +
    '         itbour.tg_size ts, ' +
    '         itbour.tg_design_page tdp, ' +
    '         itbour.itb_user iu ' +
    '    WHERE tsr.set_id IN ('+ids+') ' +
    '      AND utd.uni_item_id = tsr.uni_item_id ' +
    '      AND utd.item_type = 10 ' +
    '      AND tdd.design_id = utd.item_id ' +
    '      AND ts.size_id = tdd.size_id ' +
    '      AND tdp.design_id = tdd.design_id ' +
    '      AND tdp.page_index = 0 ' +
    '      AND iu.user_id = tdd.user_id ' +
    '      AND ystr.set_id = tsr.set_id ' +
    '      AND yst.st_id = ystr.st_id ' +
    '      AND tsr.del_flg=0 ' +
    '      AND utd.del_flg=0 ' +
    '      AND tdd.del_flg=0 ' +
    '      AND yst.del_flg=0 ' +
    '      AND ystr.del_flg=0 ' +
    '      AND ts.del_flg=0 ' +
    '      AND tdp.del_flg=0 ' +
    '      AND iu.del_flg=0 ' +
    '      AND tdd.publish = 1 ' +
    '      AND yst.publish=1 ' +
    '    UNION SELECT utd.uni_item_id AS id, ' +
    '                     vdd.design_name AS name, ' +
    '                     2 AS opType, ' +
    '                     vdd.theme_thumb AS thumb, ' +
    '                     ts.width AS w, ' +
    '                     ts.height AS h, ' +
    '                     iu.nickname AS author, ' +
    '                     DATE_FORMAT(vdd.create_time,"%Y-%m-%d %H:%i:%s") AS time, ' +
    '                     yst.title AS typeDesc, ' +
    '                     utd.order ' +
    '    FROM yjx.yjx_tmpl_set_r tsr, ' +
    '         yjx.yjx_uni_items utd, ' +
    '         yjx.yjx_show_type yst, ' +
    '         yjx.yjx_show_type_r ystr, ' +
    '         itbour.video_design_doc vdd, ' +
    '         itbour.tg_size ts, ' +
    '         itbour.itb_user iu ' +
    '    WHERE tsr.set_id IN ('+ids+') ' +
    '      AND utd.uni_item_id = tsr.uni_item_id ' +
    '      AND utd.item_type = 30 ' +
    '      AND vdd.design_id = utd.item_id ' +
    '      AND ts.size_id = vdd.size_id ' +
    '      AND iu.user_id = vdd.user_id ' +
    '      AND ystr.set_id = tsr.set_id ' +
    '      AND yst.st_id = ystr.st_id ' +
    '      AND tsr.del_flg=0 ' +
    '      AND utd.del_flg=0 ' +
    '      AND yst.del_flg=0 ' +
    '      AND ystr.del_flg=0 ' +
    '      AND vdd.del_flg=0 ' +
    '      AND ts.del_flg=0 ' +
    '      AND iu.del_flg=0 ' +
    '      AND vdd.publish=1 ' +
    '      AND yst.publish=1 ' +
    '    UNION SELECT utd.uni_item_id AS id, ' +
    '                     it.tmpl_name AS name, ' +
    '                     3 AS opType, ' +
    '                     itp.thumb_s AS thumb, ' +
    '                     1600 AS w, ' +
    '                     900 AS h, ' +
    '                     iu.nickname AS author, ' +
    '                     DATE_FORMAT(it.create_time,"%Y-%m-%d %H:%i:%s") AS time, ' +
    '                     yst.title AS typeDesc, ' +
    '                     utd.order ' +
    '    FROM yjx.yjx_tmpl_set_r tsr, ' +
    '         yjx.yjx_uni_items utd, ' +
    '         yjx.yjx_show_type yst, ' +
    '         yjx.yjx_show_type_r ystr, ' +
    '         itbour.itb_template it, ' +
    '         itbour.itb_tmpl_page itp, ' +
    '         itbour.itb_user iu ' +
    '    WHERE tsr.set_id IN ('+ids+') ' +
    '      AND utd.uni_item_id = tsr.uni_item_id ' +
    '      AND utd.item_type = 20 ' +
    '      AND it.tmpl_id = utd.item_id ' +
    '      AND iu.user_id = it.user_id ' +
    '      AND itp.tmpl_id = it.tmpl_id ' +
    '      AND itp.page_index = 0 ' +
    '      AND ystr.set_id = tsr.set_id ' +
    '      AND yst.st_id = ystr.st_id ' +
    '      AND tsr.del_flg=0 ' +
    '      AND utd.del_flg=0 ' +
    '      AND yst.del_flg=0 ' +
    '      AND ystr.del_flg=0 ' +
    '      AND it.del_flg=0 ' +
    '      AND itp.del_flg=0 ' +
    '      AND iu.del_flg=0 ' +
    '      AND yst.publish=1 ' +
    '      AND it.publish=1) mix ' +
    ' LEFT JOIN yjx.yjx_uni_tmpl_stats uts ON mix.id = uts.uni_item_id ' +
    ' AND uts.del_flg=0 ' +
    ' ORDER BY mix.order ';
    if (typeof pageNum !== 'undefined' && pageNum !== null &&
        typeof pageSize !== 'undefined' && pageSize !== null)
    {
        var skipCnt = Number(pageNum||'0')*Number(pageSize||'0');
        sql += " LIMIT " + skipCnt + "," + Number(pageSize||'0');
    }
    return sql;
}

/**
 * 获取指定范围模板组内模板列表
 *
 * @author 王俊
 * @date 2017-11-16
 *
 * @param setIds 模板组 id 数组
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param callback
 *             error: 查询出错
 *             results: 对应的模板组
 *
 * */
YjxTmplSetModel.prototype.getTmplSetsContentList = function (setIds, pageNum, pageSize,callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTmplSetModel.js [getTmplSetsContentList] getConErr' + getConErr);
            return callback(getConErr, null);
        }

        var sql = sql_getSetsTmplsList(false, setIds, pageNum, pageSize);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTmplSetModel.js [getTmplSetsContentList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })
};

/**
* 获取指定范围模板组内的模板个数
*
* @author 王俊
* @date 2017-11-16
*
* @param setIds 模板组 id 集合
* @param callback 回调
*           err: 查询失败
*           count: 数量
*
* */
YjxTmplSetModel.prototype.getTmplSetsContentListCnt = function (setIds, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTmplSetModel.js [getTmplSetsContentListCnt] getConErr: ' + getConErr);
            return callback(getConErr, null);
        }

        var sql = sql_getSetsTmplsList(true, setIds);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTmplSetModel.js [getTmplSetsContentListCnt] queryErr' + queryErr);
                return callback(queryErr, null);
            }
            if (results && results[0]) {
                return callback(queryErr, results[0].count);
            }
            return callback(queryErr,null);
        });
    })
};


YjxTmplSetModel.prototype.getAllSpecialTopics = function (limit, callback) {

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTmplSetModel.js [getAllSpecialTopics] getConErr: ' + getConErr);
            return callback(getConErr, null);
        }

        var sql =
            ' SELECT * ' +
            ' FROM yjx.yjx_tmpl_set ts ' +
            ' WHERE ts.use = 10 ' +
            '   AND ts.del_flg=0 ' +
            '   AND ts.publish=1 ' +
            ' ORDER BY ts.order, ts.create_time  ' +
            ' LIMIT ' + limit;
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTmplSetModel.js [getAllSpecialTopics] queryErr' + queryErr);
                return callback(queryErr, null);
            }
            return callback(queryErr,results);
        });
    });
};


/**
 * 获取行业分类信息
 * @param callback
 */
YjxTmplSetModel.prototype.getIndustryCondition = function (callback) {

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxTmplSetModel.js [getIndustryCondition] getConErr: ' + getConErr);
            return callback(getConErr, null);
        }

        var sql ="	SELECT	" +
                "	  *	" +
                "	FROM	" +
                "	  yjx.yjx_tmpl_set yts	" +
                "	WHERE yts.del_flg = 0	" +
                "	AND yts.publish = 1	" +
                "	AND yts.use = 1	" +
                "	ORDER BY yts.order,yts.create_time DESC	" ;
            console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxTmplSetModel.js [getIndustryCondition] queryErr' + queryErr);
                return callback(queryErr, null);
            }
            return callback(queryErr,results);
        });
    });
};










module.exports = YjxTmplSetModel;